#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
save_eml_params.py
配置写死在入口，main() 带参数，零交互
"""
import imaplib
import email
import os
import sys
from datetime import datetime
from email.header import decode_header, make_header


def safe_filename(raw: str) -> str:
    return "".join(c if c.isalnum() or c in "-_." else "_" for c in raw)


def decode_mime_words(s):
    return str(make_header(decode_header(s or "")))


def save_eml(msg_bytes, filename, out_dir):
    os.makedirs(out_dir, exist_ok=True)
    path = os.path.join(out_dir, filename)
    with open(path, "wb") as f:
        f.write(msg_bytes)
    print("[saved]", path)


def main(server, port, user, password, out_dir, use_ssl=True, limit=None, unseen=False):
    # 连接
    if use_ssl:
        imap = imaplib.IMAP4_SSL(server, port)
    else:
        imap = imaplib.IMAP4(server, port)
        imap.starttls()
    imap.login(user, password)
    imap.select("INBOX", readonly=True)

    # 搜索
    criterion = "UNSEEN" if unseen else "ALL"
    typ, msg_nums = imap.search(None, criterion)
    if typ != "OK":
        print("搜索邮件失败:", typ)
        return 1
    msg_list = msg_nums[0].split()
    if limit:
        msg_list = msg_list[-limit:]
    print(f"共 {len(msg_list)} 封邮件待导出")

    # 抓取
    for msg_id in msg_list:
        typ, data = imap.fetch(msg_id, "(RFC822)")
        if typ != "OK":
            continue
        msg_bytes = data[0][1]
        msg = email.message_from_bytes(msg_bytes)
        from_ = decode_mime_words(msg.get("From"))
        subj = decode_mime_words(msg.get("Subject"))
        try:
            dt = email.utils.parsedate_to_datetime(msg.get("Date", ""))
        except Exception:
            dt = datetime.now()
        fname = f"{safe_filename(from_)}_{safe_filename(subj)}_{dt.strftime('%Y%m%d-%H%M%S')}.eml"
        fname = fname[:120] + ".eml"
        save_eml(msg_bytes, fname, out_dir)

    imap.close()
    imap.logout()
    print("全部完成！")
    return 0


if __name__ == "__main__":
    # ======== 一次性填这里 ========
    CONFIG = {
        "server": "imap.139.com",
        "port": 993,
        "user": "sen_shan@139.com",
        "password": "8ed188d6b2404c291800",
        "out_dir": "./eml",
        "use_ssl": True,
        "limit": None,   # 最近 N 封，None=全部
        "unseen": False,  # True=只抓未读
    }
    project_root = os.getcwd()
    print(project_root)
    # =============================
    # sys.exit(main(**CONFIG))
